package cn.bluethink.eguan.core.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.bluethink.eguan.core.security.Token;
import cn.bluethink.eguan.core.service.EgMemberService;
import cn.bluethink.eguan.core.service.EgStaffService;
import cn.bluethink.eguan.core.service.EgTavernService;
import cn.bluethink.eguan.core.service.EgUserService;
import cn.bluethink.eguan.filter.NameFilter;
import cn.bluethink.eguan.filter.TavernFilter;
import cn.bluethink.eguan.model.core.EgFaction;
import cn.bluethink.eguan.model.core.EgOType;
import cn.bluethink.eguan.model.core.EgPurview;
import cn.bluethink.eguan.model.core.EgTavern;
import cn.bluethink.eguan.model.core.EgUser;
import cn.bluethink.eguan.result.PageInfo;
import cn.bluethink.eguan.result.ResponseMessage;
import cn.bluethink.eguan.result.ResponseResult;
import cn.bluethink.eguan.utils.AESUtils;

/**
 * eguan+驿馆控制器
 * 
 * @title 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.1.0
 * @describe
 * @author liuxn
 * @date 2018年10月14日
 * @note 修订历史： （1）liuxn于2018年10月14日构建初始版本0.1 （2）liuxn于2019年1月10日添加驿馆升级功能
 */
@CrossOrigin
@RestController
@RequestMapping("/eguan/v1.0/tavern")
public class EgTavernController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private EgTavernService tavernService;

    @Autowired
    private EgUserService userService;

    @Autowired
    private EgStaffService staffService;

    @Autowired
    private EgMemberService memberService;

    /**
     * 进入驿馆
     * 
     * @param egid
     * @return
     * @throws Exception
     */
    @Token
    @GetMapping("/enter")
    public ResponseResult<Long> enter(@RequestParam Long egid) throws Exception {
        // 1、获取驿馆信息
        EgTavern tavern = tavernService.getById(egid);
        if (tavern == null)
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 2、获取会话中存储的当前登录用户ID
        // String token = request.getHeader("Authorization");
        Long uid = (Long) request.getAttribute("userId");
        // 3、更新用户所在位置
        if (userService.updatePos(uid, EgOType.TAVERN, egid)) {
            return new ResponseResult<>(ResponseMessage.OK, egid);
        }
        return new ResponseResult<>(ResponseMessage.UPDATE_FAIL);
    }

    /**
     * 创建驿馆（拥有驿馆管理权限的用户可以创建驿馆）
     * 
     * @param tavern
     * @return 返回驿馆信息
     * @throws Exception
     */
    @Token(purviews = { EgPurview.CREATE_TAVERN })
    @PostMapping("/create")
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public ResponseResult<EgTavern> create(@RequestBody EgTavern tavern) throws Exception {
        // 1、获取会话中存储的当前登录用户ID
        // String token = request.getHeader("Authorization");
        Long uid = (Long) request.getAttribute("userId");
        // 2、如果驿馆名称为null,返回参数不能为空
        if (!EgTavern.isValidate(tavern))
            return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
        // 3、创建驿馆
        EgTavern result = tavernService.create(tavern, uid);
        if (result == null)
            return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
        // 4、驿馆创建成功，添加该用户为驿馆伙计
        List<Long> uids = new ArrayList<>();
        uids.add(uid);
        if (!staffService.batchAdd(tavern, uids))
            return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
        // 5、设置该用户在staff表中的角色驿馆掌柜
        if (staffService.setshopkeeper(result.getId(), uid, true) == null)
            return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
        // 6、在staff表中给予该用户驿馆管理权限
        if (staffService.setTaverMG(result.getId(), uid) == 0)
            return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
        return new ResponseResult<>(ResponseMessage.OK, result);
    }

    /**
     * 删除驿馆（拥有驿馆管理权限的用户可以删除）
     * 
     * @param egid
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.TAVERN_MG, EgPurview.OBJECT_CHECK, EgPurview.APPOINT_SHOPKEEPER })
    @PostMapping("/del")
    public ResponseResult<Long> del(@RequestParam Long egid) throws Exception {
        if (tavernService.del(egid) > 0) {
            return new ResponseResult<>(ResponseMessage.OK, egid);
        }
        return new ResponseResult<>(ResponseMessage.DELETE_FAIL, 0L);
    }

    /**
     * 更新驿馆信息（拥有驿馆管理权限的用户可以更新）
     * 
     * @param tavern
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.TAVERN_MG, EgPurview.OBJECT_CHECK, EgPurview.APPOINT_SHOPKEEPER })
    @PostMapping("/update")
    public ResponseResult<EgTavern> update(@RequestBody EgTavern tavern) throws Exception {
        // 1、如果tavern的Id为空，返回Id不能为空
        if (!tavern.isValidate())
            return new ResponseResult<>(ResponseMessage.NOTNULL_ID);
        // 判断数据库中是否存在
        EgTavern oldtavern = tavernService.detail(tavern.getId());
        if (oldtavern == null)
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
        // 2、更新驿馆信息
        EgTavern result = tavernService.update(tavern);
        if (result == null)
            return new ResponseResult<>(ResponseMessage.UPDATE_FAIL);
        return new ResponseResult<>(ResponseMessage.OK, result);
    }

    /**
     * 查看驿管详情
     * 
     * @param egid
     * @return
     * @throws Exception
     */
    @Token
    @GetMapping("/detail")
    public ResponseResult<EgTavern> detail(@RequestParam Long egid) throws Exception {
        // 1、获取驿馆信息
        EgTavern tavern = tavernService.detail(egid);
        if (tavern != null && tavern.getId() != null && tavern.getId() > 0)
            return new ResponseResult<>(ResponseMessage.OK, tavern);
        return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
    }

    /**
     * 根据条件查询驿馆列表
     * 
     * @param filter
     * @return
     * @throws Exception
     */
    @Token
    @PostMapping("/query")
    public ResponseResult<PageInfo<EgTavern>> query(@RequestBody TavernFilter filter) throws Exception {
        return new ResponseResult<>(ResponseMessage.OK, tavernService.query(filter));
    }

    /**
     * 
     * 升级驿馆为门派 只有驿馆管理权限的人可以执行此操作
     * 
     * @param egid
     * @return
     * @throws Exception
     */
    @Token(purviews = { EgPurview.TAVERN_MG })
    @PostMapping("/upgrade")
    public ResponseResult<EgFaction> upgrade(@RequestParam Long egid) throws Exception {
        // 1、获取会话中存储的当前登录用户ID
        Long uid = (Long) request.getAttribute("userId");
        EgTavern tavern = tavernService.getById(egid);
        if (tavern != null && tavern.getId() > 0) {
            // 获取驿馆伙计列表
            NameFilter filter = new NameFilter();
            filter.setId(tavern.getId());
            List<EgUser> staffs = staffService.query(filter, true).getList();
            if (staffs == null || staffs.size() == 0)
                return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
            // 这里人数暂定为10，后续做配置进行调整
            if (staffs.size() < 10)
                return new ResponseResult<>(ResponseMessage.CREATE_FAIL.getStatus(), "未达到升级条件，达到10人后即可升级，快去邀请吧！");
            EgFaction faction = tavernService.upgrade(tavern, staffs, uid);
            if (faction != null && faction.getId() > 0)
                return new ResponseResult<>(ResponseMessage.OK, faction);
            return new ResponseResult<>(ResponseMessage.CREATE_FAIL.getStatus(), "驿馆升级失败！");
        }
        return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND);
    }

    /**
     * 根据驿馆ID创建加密后的密文
     * 
     * @param egid
     * @return
     * @throws Exception
     */
    @Token
    @PostMapping("/encrypt")
    public ResponseResult<String> encrypt(@RequestParam Long egid) throws Exception {
        // 根据门派ID获取加密后的密文
        String encodeString = AESUtils.encodeASE(String.valueOf(egid));
        if (encodeString != null && !"".equals(encodeString)) {
            return new ResponseResult<>(ResponseMessage.OK, encodeString);
        }
        return new ResponseResult<>(ResponseMessage.CREATE_FAIL);
    }

    /**
     * 驿馆伙计邀请
     * 
     * @param encryption
     * @return
     * @throws Exception
     */
    @Token
    @PostMapping("/invite")
    public ResponseResult<Map<String, Long>> invite(@RequestParam String encryption) throws Exception {
        // 对密文解密
        String decodeString = AESUtils.decodeASE(encryption);
        if (decodeString == null) {
            return new ResponseResult<>(ResponseMessage.INVITE_FAIL.getStatus(), "邀请码失效，请联系相关人员重新获取！");
        }
        if (decodeString.equals("LinkRot")) {
            return new ResponseResult<>(ResponseMessage.INVITE_FAIL.getStatus(), "邀请码已过期，请重新获取！");
        }
        Long egid = Long.parseLong(decodeString);
        // 1获取用户的信息
        Long uid = (Long) request.getAttribute("userId");
        // 2获取驿馆信息
        EgTavern tavern = tavernService.getById(egid);
        if (tavern == null) {
            return new ResponseResult<>(ResponseMessage.DATA_NOT_FOUND.getStatus(), "驿馆不存在！");
        }
        // 驿馆中是否存在该用户
        EgUser staff = staffService.getById(egid, uid);
        // 获取驿馆隶属门派的门派ID
        Long fid = tavern.getFaction().getId();
        Boolean result = null;
        Map<String, Long> resultMap = new HashMap<>();
        resultMap.put("egid", egid);
        resultMap.put("fid", fid);
        // 3驿馆不存在所属门派(江湖中的驿馆)
        if (fid == null || fid == 0) {
            // 如果驿馆中存在该用户，返回驿馆ID；否则添加该用户为当前驿馆伙计，并更新位置为当前驿馆
            if (staff != null && staff.getId() != null && staff.getId() > 0) {
                return new ResponseResult<>(200, "您已是驿馆伙计！", resultMap);
            } else {
                result = tavernService.invite(egid, uid);
            }
        } else {
            if (staff != null && staff.getId() != null && staff.getId() > 0) {
                return new ResponseResult<>(200, "您已是驿馆伙计！", resultMap);
            } else {
                // 门派中存在该用户，添加该用户为当前驿馆伙计,并更新位置为当前驿馆；否则不能邀请。
                EgUser member = memberService.queryById(fid, uid);
                if (member != null) {
                    result = tavernService.invite(egid, uid);
                } else {
                    return new ResponseResult<>(ResponseMessage.INVITE_FAIL.getStatus(), "你不是该驿馆隶属门派中的成员，邀请失败！");
                }
            }
        }
        if (result != null && result) {
            return new ResponseResult<>(ResponseMessage.OK, resultMap);
        }
        return new ResponseResult<>(ResponseMessage.INVITE_FAIL);
    }
}
